﻿#include "TaskReceiver.h"

TaskReceiver::TaskReceiver(int index, QObject *parent) : MyObject(parent)
{
    equipment = globalData->equList.at(index);
    simData = globalData->simList.at(index);
    state = globalData->stateList.at(index);
    format = new FrameFormat();
    sqlbase = new SqlBase();
}

void TaskReceiver::Start(){
    MyLog::Info(QString("TaskReceiver::Start"));

    Serial serialConf;
    serialConf.serialName  = equipment->serialName;
    serialConf.baudRate    = equipment->baudRate;
    serialConf.dataBit     = equipment->dataBit;
    serialConf.checkoutBit = equipment->checkoutBit;
    serialConf.stopBit     = equipment->stopBit;

    serialPort = new SerialPort(serialConf);

    connect(serialPort, SIGNAL(SerialRead(QByteArray)), this, SLOT(ReadData(QByteArray)));
    serialPort->Start();

    timer = new QTimer;
    connect(timer, SIGNAL(timeout()), this, SLOT(OnTimer()));///定时发送串口指令///
    timer->start(100);

    timerSave=new QTimer;
    connect(timerSave,SIGNAL(timeout()),this,SLOT(SaveData()));///每秒数据入库///
    timerSave->start(1000);
    //connect(globalData,SIGNAL(seriPort()),this,SLOT(OnTimer()));///点击发送///
}

void TaskReceiver::Stop(){
    timer->stop();
    timerSave->stop();
    emit Finished();
}

void TaskReceiver::OnTimer(){
    equipment->isOnline = this->SetCmd(Instruction::CMD2);
}

void TaskReceiver::ReadData(QByteArray dataArray){


    if(dataArray.size() < 6) return;

    char *data = dataArray.data();
    if((uint8_t)data[0] != 0xEE || (uint8_t)data[1] != 0xFF){
        return;
    }
    if((uint8_t)data[3] != this->equipment->devid){
        return;
    }

    memcpy(format,dataArray.data(),dataArray.size());
    if(this->IsLittleEndian()){//为小端机时
        QByteArray humd;  humd.append(data[1]); humd.append(data[0]);
        memcpy(&(format->HEAD),humd.data(),2);
    }

    //float coe = equipment->cosjx;
    //float kw = equipment->type == 0 ? Kw_10 : Kw_50;
    JudgeData(simData, format, equipment,state);///数据赋值给结构体///

}

bool TaskReceiver::SetCmd(Instruction cmd){
    bool b = false;
    mutex.lock();

    QByteArray data;
    data.append((char)0xEE);
    data.append((char)0xFF);
    data.append((char)0x03);
    data.append((char)equipment->devid);
    data.append((char)cmd);
    data.append((char)0xAA);

    b = serialPort->SendData(data, "");

    mutex.unlock();

    return b;
}

bool TaskReceiver::IsLittleEndian(){//区分大小端 true为小端
    union{
        short a;//2字节
        char  b;//1字节
    }test;
    test.a=0x0061;//a
    return test.b == 'a';
}

void TaskReceiver::SaveData()
{
    if(!equipment->isOnline){
        return;
    }

    QDateTime datetime = QDateTime::currentDateTime();

    quint8 cmd=format->CMD;
    if(cmd==CMD2)
    {
       sqlbase->Savedata_State(state,datetime);
       sqlbase->Savedata_Sim(simData,datetime);
    }
}
